package com.kehutong.employee.controller;

import java.io.File;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.kehutong.common.interceptor.TrasIntercepter;
import com.kehutong.employee.dao.EmployeeDao;
import com.kehutong.employee.entity.*;
import com.kehutong.employee.service.PositionService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.coraframework.authz.HasPermission;
import org.coraframework.authz.Subject;
import org.coraframework.converter.Converter;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.Condition;
import org.coraframework.orm.jdbc.execute.QueryCondition;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.EnumUtil;
import org.coraframework.util.Objects;
import com.kehutong.common.DoveClient;
import com.kehutong.common.ExcelUtil;
import com.kehutong.common.entity.Root;
import com.kehutong.common.enums.Gender;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.util.Token;
import com.kehutong.employee.enums.Identity;
import com.kehutong.employee.enums.Status;
import com.kehutong.employee.enums.Type;

@MvcAction
@ReqMapping("/admin/basic/employee")
public class EmployeeController {

	@Inject
	private JdbcSession jdbcSession;
	@Inject
    private DoveClient doveClient;
    @Inject
    private FileUrlConfig fileUrlConfig;
    @Inject
    private PositionService positionService;
    @Inject
    private EmployeeDao employeeDao;

    public final static String[] EXCEL_IMPORT_HEADER = {"账号","姓名","手机号","部门","职务","是否主管(是/否)","性别","座机","邮箱","办公地点","备注","入职时间","角色"};

    @HasPermission("employee:list:view")
    @ReqMapping("/listAll")
    public Object listAll(JSONObject jsonObject) {
        List<Employee> list = jdbcSession.findArray(Employee.class)
                .in(jsonObject, "id")
                .like(jsonObject, "department", "positionNos","name")
                .eq(jsonObject, "identity")
                .eq("deleted", false)
                .order("sort", "DESC")
                .exe();

        return list;
    }

    @HasPermission("employee:list:view")
    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) throws Exception {
        Page<Employee> page = jdbcSession.findPage(Employee.class)
                .in(jsonObject,"id")
                .like(jsonObject, "department", "positionNos")
                .eq(jsonObject, "identity")
                .eq("deleted", false)
                .order("sort", "DESC")
                .page(jsonObject)
                .exe();

        Map<String, JSONObject> departmentMap = getDepartmentMap();

        page.getList().forEach(item -> {
            item.setDepName(String.join(";", item.getDepartmentName()));
            item.setDutyDepName(String.join(";", item.getDutyDepartmentName()));
            if(Objects.nonNull(item.getRoleName())){
                item.setRoleTemp(String.join(";", item.getRoleName()));
            }

            List<JSONObject> dutyDepts = new ArrayList<>();
            for (int i = 0;i < item.getDepartment().size();i++){
                JSONObject dutyDept = new JSONObject();
                JSONObject depart = departmentMap.get(item.getDepartment().get(i));
                dutyDept.put("id", depart.getString("id"));
                dutyDept.put("label", depart.getString("name"));
                dutyDepts.add(dutyDept);
            }
            item.setDutyDepartmentList(dutyDepts);

            if(Objects.nonEmpty(item.getPositionNos())){
                List<Position> positions = jdbcSession.findArray(Position.class)
                        .in("id", item.getPositionNos())
                        .eq("deleted", false)
                        .exe();
                List<String> positionNames = positions.stream().map(Position::getName).collect(Collectors.toList());
                item.setPositionNames(positionNames);
            }

            if(Objects.nonEmpty(jsonObject.getString("positionNos"))){
                PositionDepartment department = jdbcSession.findOne(PositionDepartment.class)
                        .eq("positionId", jsonObject.getString("positionNos"))
                        .eq("userId", item.getId())
                        .eq("deleted", false)
                        .exe();

                if(Objects.nonNull(department) && Objects.nonNull(department.getDepartmentNos())){
                    List<String> positionDepartment = new ArrayList<>();
                    department.getDepartmentNos().forEach(id -> {
                        JSONObject depart = departmentMap.get(id);
                        if(Objects.nonNull(depart)){
                            positionDepartment.add(depart.getString("name"));
                        }
                    });
                    item.setPositionDepartment(positionDepartment);
                }
            }
        });
        return page;
    }

    @HasPermission("employee:list:view")
    @ReqMapping("/merge/list")
    public Object mergeList(JSONObject jsonObject) throws Exception {
        List<Employee> employees = jdbcSession.findArray(Employee.class)
                .like(jsonObject, "name")
                .exe();
        JSONArray departments = getDepartments(null, jsonObject.getString("name"));

        JSONObject result = new JSONObject();
        result.put("employees", employees);
        result.put("departments", departments);

        return result;
    }

    @HasPermission("employee:list:view")
    @ReqMapping("/buildEmployees")
    public Object buildEmployees(Token token, JSONObject jsonObject) throws Exception {
        JSONArray ids = jsonObject.getJSONArray("id");
        if(Objects.isEmpty(ids)){
            return new Page<>();
        }

        Page<Employee> page = jdbcSession.findPage(Employee.class)
                .in(jsonObject,"id")
                .like(jsonObject, "department")
                .page(jsonObject)
                .exe();

        for (Employee item: page.getList()) {
            item.setDutyDepName(String.join(";", item.getDutyDepartmentName()));
            item.setDepName(String.join(";", item.getDepartmentName()));
            if(Objects.nonNull(item.getRoleName())){
                item.setRoleTemp(String.join(";", item.getRoleName()));
            }

            List<String> build = getBuild(token, item.getId(), jsonObject.getString("communityNo"));
            if(Objects.nonEmpty(build)){
                item.setBuild(String.join(",", build));
            }
        }
        return page;
    }

    @HasPermission("employee:list:view")
    @ReqMapping("/get")
    public Object get(Token token, Employee employee) throws Exception {

        if(Objects.isNull(employee)){
            return Result.error(0, "暂未获取到员工信息");
        }

        employee.setDepName(String.join(";", employee.getDepartmentName()));
        employee.setDutyDepName(String.join(";", employee.getDutyDepartmentName()));

        List<String> departmentIds = employee.getDepartment();
        if(Objects.nonEmpty(departmentIds)){
            Map<String,JSONObject> departmentMap = getDepartmentMap(departmentIds, null);
            List<JSONObject> departments = new ArrayList<>();

            List<JSONObject> dutyDepts = new ArrayList<>();
            departmentIds.forEach(id -> {
                JSONObject entity = departmentMap.get(id);
                if(Objects.nonEmpty(entity)){
                    departments.add(entity);

                    JSONObject dutyDept = new JSONObject();
                    dutyDept.put("id", entity.getString("id"));
                    dutyDept.put("label", entity.getString("name"));
                    dutyDepts.add(dutyDept);
                }
            });
            employee.setDutyDepartmentList(dutyDepts);
            employee.setDepartmentList(departments);
        }

        if(Objects.nonEmpty(employee.getPositionNos())){
            List<Position> positions = jdbcSession.findArray(Position.class)
                    .in("id", employee.getPositionNos())
                    .eq("deleted", false)
                    .exe();
            List<String> positionNames = positions.stream().map(Position::getName).collect(Collectors.toList());
            employee.setPositionNames(positionNames);
        }

        return employee;
    }

    @ReqMapping("/enums")
    public Object getEnums(JSONObject jsonObject) {
        Map<String, Object> map = new HashMap<>();
        map.put("genders", Arrays.asList(Gender.values()));
        map.put("identitys", Arrays.asList(Identity.values()));
        map.put("statuses", Arrays.asList(Status.values()));
        map.put("types", Arrays.asList(Type.values()));

        List<Position> positions = jdbcSession.findArray(Position.class)
                .like(jsonObject, "name")
                .eq("deleted", false)
                .exe();
        map.put("positions", positions);
        return Result.success(map);
    }

    @TrasIntercepter("/wwin/employee/wwin/create")
    @Bean(newInstance=true, copy=true)
    @HasPermission("employee:form:save")
    @ReqMapping("/save")
    public Object save(Employee item, JSONObject jsonObject) throws Exception {
        Employee employee = jdbcSession.findOne(Employee.class)
                .eq("userid", item.getUserid())
                .eq("deleted", false)
                .exe();

        if(Objects.nonNull(employee)){
            return Result.error(0,"员工账号不能重复");
        }

        setProperty(item, jsonObject);


        QueryCondition query = Condition.createQuery(false);
        Map<String,Object> rs = employeeDao.getMaxSort(query);
        item.setSort(Long.valueOf(rs.get("sort").toString()));

    	jdbcSession.insert(item);
        return Result.success();
    }


    @HasPermission("employee:form:edit")
    @ReqMapping("/updateSort")
    public Object updateSort(JSONObject jsonObject) {
        JSONArray array = jsonObject.getJSONArray("data");
        for (int i = 0; i < array.size(); i ++) {
            JSONObject json = array.getJSONObject(i);
            Employee employee = Pool.get(Employee.class, json.getString("id"));
            employee.setSort(json.getLong("sort"));
            jdbcSession.updateById(employee);
        }
        return Result.success();
    }

    @HasPermission("employee:form:update")
    @ReqMapping("/updatePosition")
    public Object updatePosition(JSONObject jsonObject) throws Exception {
        JSONArray employeeNos = jsonObject.getJSONArray("employees");
        String position = jsonObject.getString("position");
        Boolean isSave = jsonObject.getBoolean("isSave");

        List<Employee> employees = jdbcSession.findArray(Employee.class)
                .in("id", employeeNos)
                .exe();

        employees.forEach(item ->{
            Set<String> positionNos = new HashSet<>(item.getPositionNos());
            if(isSave) {
                PositionDepartment entity = jdbcSession.findOne(PositionDepartment.class)
                        .eq("positionId", position)
                        .eq("userId", item.getId())
                        .eq("deleted", false)
                        .exe();
                if(Objects.isNull(entity)){
                    entity = Pool.newInstance(PositionDepartment.class);
                    entity.setPositionId(position);
                    entity.setUserId(item.getId());
                    jdbcSession.insert(entity);
                }
                positionNos.add(position);
            }else{
                PositionDepartment entity = jdbcSession.findOne(PositionDepartment.class)
                        .eq("positionId", position)
                        .eq("userId", item.getId())
                        .eq("deleted", false)
                        .exe();
                entity.setDeleted(false);

                jdbcSession.updateById(entity);

                positionNos.remove(position);
            }
            item.setPositionNos(new ArrayList<>(positionNos));
        });

        jdbcSession.updateById(employees);

        return Result.success();
    }

    @TrasIntercepter("/wwin/employee/wwin/update")
    @Bean(copy=true)
    @HasPermission("employee:form:update")
    @ReqMapping("/update")
    public Object update(Employee item, JSONObject jsonObject) throws Exception {
        Employee employee = jdbcSession.findOne(Employee.class)
                .eq("userid", item.getUserid())
                .noEq("id", item.getId())
                .eq("deleted", false)
                .exe();

        if(Objects.nonNull(employee)){
            return Result.error(0,"员工账号不能重复");
        }

        setProperty(item, jsonObject);

    	jdbcSession.updateById(item);
        return Result.success();
    }

    @HasPermission("employee:form:edit")
    @ReqMapping("/updateDepartment")
    public Object updateDepartment(JSONObject jsonObject) throws Exception {
        JSONArray checkedList = jsonObject.getJSONArray("checkedList");

        String type = jsonObject.getString("type");

        JSONArray department = jsonObject.getJSONArray("department");
        JSONArray departmentName = jsonObject.getJSONArray("departmentName");

        List<Employee> employees = jdbcSession.findArray(Employee.class)
                .in("id", checkedList)
                .exe();

        // 修改职务部门
        if(Objects.nonEmpty(type) && type.equals("position")){
            String positionId = jsonObject.getString("positionId");
            List<String> departments = JSONObject.parseArray(department.toString(),String.class);
            employees.forEach(item -> {
                PositionDepartment entity = jdbcSession.findOne(PositionDepartment.class)
                        .eq("positionId", positionId)
                        .eq("userId", item.getId())
                        .eq("deleted", false)
                        .exe();
                entity.setDepartmentNos(departments);
                jdbcSession.updateById(entity);
            });
        // 修改主管/上级部门
        }else if (Objects.nonEmpty(type) && type.equals("duty")) {
            employees.forEach(item -> {
                item.setDutyDepartment(JSONObject.parseArray(department.toString(),String.class));
                item.setDutyDepartmentName(JSONObject.parseArray(departmentName.toString(),String.class));
            });
        // 修改所属部门
        } else {
            employees.forEach(item -> {
                item.setDepartment(JSONObject.parseArray(department.toString(),String.class));
                item.setDepartmentName(JSONObject.parseArray(departmentName.toString(),String.class));
            });
        }

        jdbcSession.updateById(employees);

        return Result.success();
    }

    @HasPermission("employee:form:delete")
    @ReqMapping("/delete")
    public Object delete(Employee item) throws Exception {
        item.setDeleted(true);
        jdbcSession.updateById(item);
    	
    	return Result.success();
    }

    @TrasIntercepter("/wwin/employee/wwin/batch/delete")
    @HasPermission("employee:form:delete")
    @ReqMapping("/batch/delete")
    public Object batchDelete(JSONObject jsonObject) throws Exception {

        List<Employee> list = jdbcSession.findArray(Employee.class)
                .in("id", jsonObject.getJSONArray("ids"))
                .exe();
        list.forEach(item -> {
            item.setDeleted(true);
            jdbcSession.updateById(item);
        });

        return Result.success();
    }

    @ReqMapping("/upload")
    public Object upload(JSONObject jsonObject) throws Exception {
        InputStream is = fileUrlConfig.download(jsonObject.getString("fileId"));
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);

        List<JSONObject> jsons = new ArrayList<>();
        EmployeeUploadLog log = Pool.newInstance(EmployeeUploadLog.class);
        Map<Integer,EmployeeUploadLogItem> errorItemMap = new HashMap<>();
        // 第4行 开始读
        for (int rIndex = sheet.getFirstRowNum() + 3; rIndex <= sheet.getLastRowNum(); rIndex++) {
            Row row = sheet.getRow(rIndex);

            String userId = ExcelUtil.getCellValue(row.getCell(0));
            String name = ExcelUtil.getCellValue(row.getCell(1));
            String mobile = ExcelUtil.getCellValue(row.getCell(2));
            String department = ExcelUtil.getCellValue(row.getCell(3));
            String positionName = ExcelUtil.getCellValue(row.getCell(4));
            String identity = ExcelUtil.getCellValue(row.getCell(5));
            String gender = ExcelUtil.getCellValue(row.getCell(6));
            String telephone = ExcelUtil.getCellValue(row.getCell(7));
            String email = ExcelUtil.getCellValue(row.getCell(8));
            String officeAddress = ExcelUtil.getCellValue(row.getCell(9));
            String remark = ExcelUtil.getCellValue(row.getCell(10));
            String entryDate = Converter.toString(ExcelUtil.getLocalDateFromCell(row, 11));
            String roleName = ExcelUtil.getCellValue(row.getCell(12));

            JSONObject json = new JSONObject();
            json.put("mobile", mobile);
            json.put("rIndex", rIndex);
            json.put("userid", userId);
            json.put("name", name);
            json.put("mobile", mobile);
            json.put("department", department);
            json.put("positionName", positionName);
            json.put("identity", identity);
            json.put("gender", gender);
            json.put("telephone", telephone);
            json.put("email", email);
            json.put("officeAddress", officeAddress);
            json.put("remark", remark);
            json.put("entryDate", entryDate);
            json.put("roleName", roleName);

            if (Objects.isEmpty(userId)) {
                json.put("msg", "【账号】不能为空");
                addErrors(errorItemMap, json);
            }

            if (Objects.isEmpty(name)) {
                json.put("msg", "【姓名】不能为空");
                addErrors(errorItemMap, json);
            }

            if (Objects.isEmpty(mobile)) {
                json.put("msg", "【手机号】不能为空");
                addErrors(errorItemMap, json);
            }

            if (Objects.isEmpty(department)) {
                json.put("msg", "【部门】不能为空");
                addErrors(errorItemMap, json);
            }

            if (Objects.nonEmpty(positionName)){
                String[] positionNames = positionName.split(",");
                for (String temp: positionNames) {
                    Position position = jdbcSession.findOne(Position.class)
                            .eq("name", temp)
                            .eq("deleted", false)
                            .exe();
                    if(Objects.isNull(position)){
                        json.put("msg", "【职务】-【" + temp +"】解析失败");
                        addErrors(errorItemMap, json);
                        break;
                    }
                }
            }

            EmployeeUploadLogItem errorItem = errorItemMap.get(rIndex);
            if(Objects.isNull(errorItem)){
                jsons.add(json);
            }
        }

        Integer size = jsons.size() + errorItemMap.size();
        if(size > 3000){
            log.setErrorCount(size);
            log.setSuccessCount(0);

            EmployeeUploadLogItem item = Pool.newInstance(EmployeeUploadLogItem.class);
            item.setError(Arrays.asList("最多支持导入3000条数据"));
            jdbcSession.insert(item);

            log.setItems(Arrays.asList(item.getId()));
            jdbcSession.insert(log);

            log.setLogItems(Arrays.asList(item));
        }

        // 数据读取结果
        if (!errorItemMap.isEmpty()) {
            List<String> items = new ArrayList<>();
            List<EmployeeUploadLogItem> logItems = new ArrayList<>();
            for (int key: errorItemMap.keySet()) {
                EmployeeUploadLogItem item = errorItemMap.get(key);
                jdbcSession.insert(item);
                items.add(item.getId());
                logItems.add(item);
            }
            log.setItems(items);
            log.setErrorCount(errorItemMap.size());
            log.setSuccessCount(size - errorItemMap.size());
            jdbcSession.insert(log);

            log.setLogItems(logItems);
        }else{
            log.setErrorCount(errorItemMap.size());
            log.setSuccessCount(size - errorItemMap.size());
            jdbcSession.insert(log);
        }

        List<String> departments = new ArrayList<>();
        for (JSONObject json: jsons) {
            departments.add(json.getString("department"));
        }

        Map<String,JSONObject> departmentMap = getDisposeDepartment(departments);

        for (JSONObject json: jsons) {
            Employee employee =  jdbcSession.findOne(Employee.class)
                    .eq(json, "userid")
                    .eq("deleted", false)
                    .exe();

            if(Objects.nonNull(employee)){
                setEmployee(employee, json, departmentMap);
                jdbcSession.updateById(employee);
            }else{
                employee = Pool.newInstance(Employee.class);
                setEmployee(employee, json, departmentMap);

                QueryCondition query = Condition.createQuery(false);
                Map<String,Object> rs = employeeDao.getMaxSort(query);
                employee.setSort(Long.valueOf(rs.get("sort").toString()));

                jdbcSession.insert(employee);
            }
        }

        return Result.success(log);
    }

    @ReqMapping("/upload/log")
    public Object uploadLog(JSONObject jsonObject) throws Exception {
        List<EmployeeUploadLog> logs = jdbcSession.findArray(EmployeeUploadLog.class)
                .order("createTime", "DESC")
                .exe();
        return Result.success(logs);
    }

    @ReqMapping("/log/export")
    public Object logExport(JSONObject jsonObject) throws Exception {
        List<EmployeeUploadLogItem> logItems = jdbcSession.findArray(EmployeeUploadLogItem.class)
                .in("id", jsonObject.getJSONArray("items"))
                .exe();

        Workbook wb = generateLogItemWorkBook(logItems);

        File tmpFile = ExcelUtil.writeXlsFile(wb, "通讯录导入异常信息", ".xlsx");

        return Result.download(tmpFile);
    }

    @ReqMapping("/checkFile")
    public Object checkFile(Token token, JSONObject jsonObject) throws Exception {
        InputStream is = fileUrlConfig.download(jsonObject.getString("fileId"));
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);

        // 3行表头 开始读
        Row firstRow = sheet.getRow(sheet.getFirstRowNum() + 2);
        List<String> errMsgs = new ArrayList<>();

        for (int i = firstRow.getFirstCellNum(); i < firstRow.getLastCellNum(); i++) {
            firstRow.getCell(i).setCellType(CellType.STRING);
            String s = firstRow.getCell(i).getStringCellValue();
            if (i < EXCEL_IMPORT_HEADER.length) {
                if (!EXCEL_IMPORT_HEADER[i].equals(s)) {
                    errMsgs.add("请确认【" + EXCEL_IMPORT_HEADER[i] + "】为第" + (i + 1) + "列");
                }
            }
        }

        JSONObject errorJson = new JSONObject();

        // 表头校验结果
        if (!errMsgs.isEmpty()) {
            errorJson.put("normalCount", 0);
            errorJson.put("errCount", 0);
            errorJson.put("successCount", 0);
            errorJson.put("errMsgs", errMsgs);
            return Result.error(0, "数据解析异常", errorJson);
        }

        Map<Integer,Integer> errorCount = new HashMap<>();
        Integer size = 0;

        // 第4行开始遍历获取数据
        for (int rIndex = sheet.getFirstRowNum() + 3; rIndex <= sheet.getLastRowNum(); rIndex++) {
            Row row = sheet.getRow(rIndex);
            String userId = ExcelUtil.getCellValue(row.getCell(0));
            if (Objects.isEmpty(userId)) {
                errorCount.put(rIndex, 1);
                errMsgs.add("第" + rIndex + "行：【账号】不能为空");
            }

            String name = ExcelUtil.getCellValue(row.getCell(1));
            if (Objects.isEmpty(name)) {
                errorCount.put(rIndex, 1);
                errMsgs.add("第" + rIndex + "行：【姓名】不能为空");
            }

            String mobile = ExcelUtil.getCellValue(row.getCell(2));
            if (Objects.isEmpty(mobile)) {
                errorCount.put(rIndex, 1);
                errMsgs.add("第" + rIndex + "行：【手机号】不能为空");
            }

            String department = ExcelUtil.getCellValue(row.getCell(3));
            if (Objects.isEmpty(department)) {
                errorCount.put(rIndex, 1);
                errMsgs.add("第" + rIndex + "行：【部门】不能为空");
            }

            String positionName = ExcelUtil.getCellValue(row.getCell(4));
            if (Objects.nonEmpty(positionName)){
                String[] positionNames = positionName.split(",");
                for (String temp: positionNames) {
                    Position position = jdbcSession.findOne(Position.class)
                            .eq("name", temp)
                            .eq("deleted", false)
                            .exe();
                    if(Objects.isNull(position)){
                        errorCount.put(rIndex, 1);
                        errMsgs.add("第" + rIndex + "行：【职务】-【" + temp +"】解析失败");
                        break;
                    }
                }
            }

            size++;
        }

        errorJson.put("normalCount", size);
        if(size > 3000){
            errMsgs = new ArrayList<>();
            errMsgs.add("最多支持导入3000条数据");
            errorJson.put("errCount", 0);
            errorJson.put("successCount", 0);
            errorJson.put("errMsgs", errMsgs);
            return Result.error(0, "数据解析异常", errorJson);
        }

        // 数据读取结果
        if (!errMsgs.isEmpty()) {
            int errSum = 0;
            for (int val: errorCount.keySet()) {
                errSum++;
            }
            errorJson.put("errMsgs", errMsgs);
            errorJson.put("errCount", errSum);
            errorJson.put("successCount", size - errSum);

            return Result.error(0, "数据解析异常", errorJson);
        }

        errorJson.put("errMsgs", errMsgs);
        errorJson.put("errCount", 0);
        errorJson.put("successCount", size);
        return Result.success("成功", errorJson);
    }

    public void addErrors(Map<Integer, EmployeeUploadLogItem> errorItemMap, JSONObject json) {
        EmployeeUploadLogItem errorItem = errorItemMap.get(json.getInteger("rIndex"));
        if(Objects.isNull(errorItem)){
            errorItem = Pool.newInstance(EmployeeUploadLogItem.class);
            errorItem.setDepartment(json.getString("department"));
            errorItem.setMobile(json.getString("mobile"));
            errorItem.setUserid(json.getString("userid"));
            errorItem.setName(json.getString("name"));
            errorItem.setRowIndex(json.getInteger("rIndex"));
            errorItem.setEmail(json.getString("email"));
            errorItem.setGender(json.getString("gender"));
            errorItem.setEntryDate(json.getString("entryDate"));
            errorItem.setIdentity(json.getString("identity"));
            errorItem.setPosition(json.getString("positionName"));
            errorItem.setTelephone(json.getString("telephone"));
            errorItem.setOfficeAddress(json.getString("officeAddress"));
            errorItem.setRemark(json.getString("remark"));
            errorItem.setRoleName(json.getString("roleName"));
        }
        List<String> errors = errorItem.getError();
        if(Objects.isEmpty(errors)){
            errors = new ArrayList<>();
        }
        errors.add(json.getString("msg"));
        errorItem.setError(errors);
        errorItemMap.put(json.getInteger("rIndex"), errorItem);
    }

    @HasPermission("wwout:employee:edit")
    @ReqMapping("/readFileSyncName")
    public Object readFileSyncName(String fileId) throws Exception {
        InputStream is = fileUrlConfig.download(fileId);
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);

        for (int rIndex = sheet.getFirstRowNum(); rIndex <= sheet.getLastRowNum(); rIndex++) {
            Row row = sheet.getRow(rIndex);
            String id = ExcelUtil.getCellValue(row.getCell(0));
            Employee employee = Pool.get(Employee.class, id);
            if (Objects.nonNull(employee)) {
                String name = ExcelUtil.getCellValue(row.getCell(1));
                employee.setName(name);
                jdbcSession.updateById(employee);
            }
        }

        return Result.success();
    }

    @ReqMapping("/updateName")
    public Object updateName(JSONObject jsonObject) throws Exception {
        JSONArray jsonArray = jsonObject.getJSONArray("employees");
        List<Employee> employeeList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject each = (JSONObject) jsonArray.get(i);
            Employee employee = Pool.get(Employee.class, each.getString("id"));
            if (Objects.nonNull(employee) && !Objects.equal(employee.getName(), each.getString("name"))) {
                employee.setName(each.getString("name"));
                employeeList.add(employee);
            }
        }
        if (employeeList.size() > 0) {
            jdbcSession.updateById(employeeList);

            doveClient.post("/kht-bin/auth/user/updateNames", http-> {
                JSONObject body = new JSONObject();
                JSONArray array = new JSONArray();
                for (Employee each : employeeList) {
                    JSONObject eachEmployee = new JSONObject();
                    eachEmployee.put("id", each.getId());
                    eachEmployee.put("name", each.getName());
                    array.add(eachEmployee);
                }

                body.put("users", array);
                http.setBody(body.toJSONString());
            });
        }
        return Result.success();
    }

    @ReqMapping("/readFile")
    public Object readFile(Token token, JSONObject jsonObject) throws Exception {

        InputStream is = fileUrlConfig.download(jsonObject.getString("fileId"));
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);

        List<JSONObject> jsons = new ArrayList<>();
        // 第4行开始遍历获取数据
        for (int rIndex = sheet.getFirstRowNum() + 3; rIndex <= sheet.getLastRowNum(); rIndex++) {
            Row row = sheet.getRow(rIndex);
            String userId = ExcelUtil.getCellValue(row.getCell(0));
            String name = ExcelUtil.getCellValue(row.getCell(1));
            String mobile = ExcelUtil.getCellValue(row.getCell(2));
            String department = ExcelUtil.getCellValue(row.getCell(3));
            String positionName = ExcelUtil.getCellValue(row.getCell(4));

            LocalDate entryDate = ExcelUtil.getLocalDateFromCell(row, 11);

            JSONObject json = new JSONObject();
            json.put("userid", userId);
            json.put("name", name);
            json.put("mobile", mobile);
            json.put("department", department);
            json.put("positionName", positionName);
            json.put("identity", ExcelUtil.getCellValue(row.getCell(5)));
            json.put("gender", ExcelUtil.getCellValue(row.getCell(6)));
            json.put("telephone", ExcelUtil.getCellValue(row.getCell(7)));
            json.put("email", ExcelUtil.getCellValue(row.getCell(8)));
            json.put("officeAddress", ExcelUtil.getCellValue(row.getCell(9)));
            json.put("remark", ExcelUtil.getCellValue(row.getCell(10)));
            json.put("entryDate", Converter.toString(entryDate));
            json.put("roleName", ExcelUtil.getCellValue(row.getCell(12)));

            jsons.add(json);
        }

        List<String> departments = new ArrayList<>();
        for (JSONObject json: jsons) {
            departments.add(json.getString("department"));
        }

        Map<String,JSONObject> departmentMap = getDisposeDepartment(departments);

        for (JSONObject json: jsons) {
            Employee employee =  jdbcSession.findOne(Employee.class)
                    .eq(json, "userid")
                    .eq("deleted", false)
                    .exe();

            if(Objects.nonNull(employee)){
                setEmployee(employee, json, departmentMap);
                jdbcSession.updateById(employee);
            }else{
                employee = Pool.newInstance(Employee.class);
                setEmployee(employee, json, departmentMap);

                QueryCondition query = Condition.createQuery(false);
                Map<String,Object> rs = employeeDao.getMaxSort(query);
                employee.setSort(Long.valueOf(rs.get("sort").toString()));

                jdbcSession.insert(employee);
            }
        }

        return Result.success();
    }

    @ReqMapping("/export")
    public Object export(JSONObject jsonObject) throws Exception {

        File tmpFile = null;
        Boolean isModel = jsonObject.getBoolean("isModel");

        if(isModel){
            Workbook wb = generateWorkBook();

            tmpFile = ExcelUtil.writeXlsFile(wb, "通讯录模板", ".xlsx");
        }else{
            FindPage<Employee> find = jdbcSession.findPage(Employee.class)
                    .eq("deleted", false)
                    .order("createTime","desc");

            JSONArray array = jsonObject.getJSONArray("department");
            if(Objects.nonEmpty(array)){
                find.markBegin();
                for (int i = 0; i < array.size(); i++) {
                    String id = array.getString(i);
                    if(Objects.equal(id, Root.ROOT_ID)){
                        find.findInSet("department", id).or();
                    }else{
                        find.like("department", id).or();
                    }
                }
                find.markEnd();
            }

            find.page(1,3000);
            Page<Employee> page = find.exe();

            Set<String> departmentSet = new HashSet<>();
            page.getList().forEach(item->{
                departmentSet.addAll(item.getDepartment());
            });
            Map<String, JSONObject> departmentMap = getDepartmentMap(new ArrayList<>(departmentSet), null);

            Workbook wb = generateWorkBook(page.getList());

            tmpFile = ExcelUtil.writeXlsFile(wb, "通讯录", ".xlsx");
        }

        return Result.download(tmpFile);
    }

    private void setProperty(Employee item, JSONObject jsonObject) throws Exception{
        String gender = jsonObject.getString("gender");
        if(Objects.isNull(gender)){
            item.setGender(Gender.NOMORE);
        }else{
            item.setGender(EnumUtil.getEnum(Gender.class, gender));
        }

        String identity = jsonObject.getString("identity");
        if(Objects.nonNull(identity)){
            item.setIdentity(EnumUtil.getEnum(Identity.class, identity));
            if(!Identity.LEAD.getId().equals(identity)){
                item.setDutyDepartment(null);
                item.setDutyDepartmentName(null);
            }
            updateEmployee(item.getDutyDepartment(), item);
        } else {
            item.setDutyDepartment(null);
            item.setDutyDepartmentName(null);
        }

        String type = jsonObject.getString("type");
        if(Objects.nonNull(type)){
            item.setType(EnumUtil.getEnum(Type.class, type));
        }

        String status = jsonObject.getString("status");
        if(Objects.nonNull(status)){
            item.setStatus(EnumUtil.getEnum(Status.class, status));
        }

        if(Objects.nonEmpty(item.getPositionNos())){
            item.getPositionNos().forEach(positionId -> {
                PositionDepartment entity = jdbcSession.findOne(PositionDepartment.class)
                        .eq("positionId", positionId)
                        .eq("userId", item.getId())
                        .eq("deleted", false)
                        .exe();

                if(Objects.isNull(entity)){
                    entity = Pool.newInstance(PositionDepartment.class);
                    entity.setPositionId(positionId);
                    entity.setUserId(item.getId());
                    jdbcSession.insert(entity);
                }
            });
        }
    }

    private void updateEmployee(List<String> ids, Employee employee) throws Exception{
        Employee oldEmployee = Pool.get(Employee.class, employee.getId());

        doveClient.post("/basic/department/service/updateEmployee", http -> {
            JSONObject body = new JSONObject();
            body.put("ids", ids);
            if(Objects.nonNull(oldEmployee)){
                body.put("oldIds", oldEmployee.getDutyDepartment());
            }
            body.put("employeeId", employee.getId());
            body.put("employeeName", employee.getName());
            http.setBody(body.toJSONString());
        });
    }

    public List<String> getBuild(Token token, String employeeNo, String communityNo) throws Exception {
        JSONObject result = doveClient.post("/basic/building/service/list", http->{
            http.addHeader("companyNo", token.getCompanyNo());

            JSONObject body = new JSONObject();
            body.put("employeeNos", employeeNo);
            body.put("communityNo", communityNo);
            http.setBody(body.toString());
        });

        JSONArray data = result.getJSONArray("data");

        if (Objects.isNull(data)) {
            return null;
        }

        List<String> list = new ArrayList<>();
        for (Object item: data) {
            JSONObject build = (JSONObject) item;
            StringBuffer buf = new StringBuffer();
            buf.append(build.getString("name"));
            if(Objects.nonEmpty(build.getString("unitName"))){
                buf.append(build.getString("unitName"));
            }
            list.add(buf.toString());
        }

        return list;
    }

    private void setEmployee(Employee employee, JSONObject json, Map<String,JSONObject> departmentMap) throws Exception {
        employee.setUserid(json.getString("userid"));
        employee.setName(json.getString("name"));
        employee.setMobile(json.getString("mobile"));


        String positionName = json.getString("positionName");
        List<String> positionNos = new ArrayList<>();
        if (Objects.nonEmpty(positionName)){
            String[] positionNames = positionName.split(",");
            for (String temp: positionNames) {
                Position position = jdbcSession.findOne(Position.class)
                        .eq("name", temp)
                        .eq("deleted", false)
                        .exe();
                if(Objects.nonNull(position)){
                    positionNos.add(position.getId());
                }
            }
        }

        employee.setPositionNos(positionNos);
        employee.setTelephone(json.getString("telephone"));
        employee.setEmail(json.getString("email"));
        employee.setOfficeAddress(json.getString("officeAddress"));
        employee.setRemark(json.getString("remark"));
        employee.setEntryDate(json.getString("entryDate"));

        String identity = json.getString("identity");
        if(Objects.nonNull(identity)){
            if(identity.equals("是")){
                employee.setIdentity(Identity.LEAD);
            }else{
                employee.setIdentity(Identity.EMPLOYEE);
            }
        }else{
            employee.setIdentity(null);
        }

        employee.setGender(Gender.getGender(json.getString("gender")));

        String department = json.getString("department");
        List<String> departments = Arrays.asList(department.split(","));

        List<String> departmentNos = new ArrayList<>();
        List<String> departmentNames = new ArrayList<>();

        for (String dep: departments) {
            List<String> deps = Arrays.asList(dep.split("-"));
            String pid = Root.ROOT_ID;
            for (String name: deps) {
                //  查询到组织部门
                JSONObject depJson = departmentMap.get(name + "-" + pid);
                pid = depJson.getString("id");
                // 只插入最后一个节点部门的信息
                if(deps.get(deps.size() - 1).equals(name)){
                    departmentNos.add(depJson.getString("id"));
                    departmentNames.add(depJson.getString("name"));
                }
            }
        }
        employee.setDepartment(departmentNos);
        employee.setDepartmentName(departmentNames);
    }

    public Map<String,JSONObject> getDepartmentMap(List<String> departmentIds, String name) throws Exception {
        JSONArray result = getDepartments(departmentIds, name);
        Map<String,JSONObject> departmentMap = new HashMap<>();
        result.forEach(item->{
            JSONObject obj = (JSONObject) item;
            departmentMap.put(obj.getString("id"), obj);
        });
        return departmentMap;
    }

    public Map<String,JSONObject> getDepartmentMap() throws Exception {
        JSONArray result = getDepartments();
        Map<String,JSONObject> departmentMap = new HashMap<>();
        result.forEach(item->{
            JSONObject obj = (JSONObject) item;
            departmentMap.put(obj.getString("id"), obj);
        });
        return departmentMap;
    }

    public JSONArray getDepartments(List<String> departmentIds, String name) throws Exception {
        JSONObject result = doveClient.post("/basic/department/service/list", http->{
            JSONObject body = new JSONObject();
            if(Objects.nonNull(departmentIds)){
                body.put("id", departmentIds);
            }
            if(Objects.nonEmpty(name)){
                body.put("name", name);
            }
            http.setBody(body.toString());
        });
        JSONArray data = result.getJSONArray("data");
        if (Objects.isNull(result) || Objects.isNull(data)) {
            return new JSONArray();
        }
        return data;
    }

    public JSONArray getDepartments() throws Exception {
        JSONObject result = doveClient.post("/basic/department/service/list", http->{});
        JSONArray data = result.getJSONArray("data");
        if (Objects.isNull(result) || Objects.isNull(data)) {
            return new JSONArray();
        }
        return data;
    }

    public Map<String,JSONObject> getDisposeDepartment(List<String> departments) throws Exception {
        JSONObject result = doveClient.post("/basic/department/service/disposeDepartment", http->{
            JSONObject body = new JSONObject();
            body.put("departments", departments);

            http.setBody(body.toString());
        });

        JSONArray data = result.getJSONArray("data");

        if (Objects.isNull(result) || Objects.isNull(data)) {
            return new HashMap<>();
        }

        Map<String,JSONObject> departmentMap = new HashMap<>();
        data.forEach(item->{
            JSONObject obj = (JSONObject) item;
            String name = obj.getString("name");
            String parent_id = obj.getString("parent_id");
            String key = name + "-" + parent_id;
            departmentMap.put(key, obj);
        });

        return departmentMap;
    }

    private Sheet setSheetCellStyle(XSSFWorkbook wb){
        //设置字体颜色+文字水平居中
        CellStyle fontColorCellStyle = wb.createCellStyle();
        XSSFFont font = wb.createFont();
        XSSFColor color = new XSSFColor(new java.awt.Color(255,0,0));
        font.setColor(color);
//        fontColorCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        fontColorCellStyle.setAlignment(HorizontalAlignment.CENTER);
        fontColorCellStyle.setFont(font);

        // 允许文字换行
        XSSFFont fontStyle = wb.createFont(); // 字体样式
//        fontStyle.setBoldweight(Font.BOLDWEIGHT_BOLD); // 加粗
        fontStyle.setBold(true);// 加粗
        fontStyle.setFontName("宋体");
        fontStyle.setFontHeightInPoints((short) 16); // 大小
        CellStyle noticeCellStyle = wb.createCellStyle();
        noticeCellStyle.setWrapText(true);
        noticeCellStyle.setFont(fontStyle);

        // 文字水平居中
        CellStyle fontCellStyle = wb.createCellStyle();
//        fontCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        fontCellStyle.setAlignment(HorizontalAlignment.CENTER);

        Sheet sheet = wb.createSheet();
        // 设置第1行 合并12格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 12));
        // 设置第2行 合并11格
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 11));

        //第1行 须知内容
        Row noticeRow = sheet.createRow(0);
        Cell noticeRowCell = noticeRow.createCell(0);
        noticeRowCell.setCellStyle(noticeCellStyle);
        StringBuffer notice = new StringBuffer();
        notice.append("填写须知：").append("\n")
                .append("<1>不能在本excel表中对员工信息类别进行增加、删除、修改，若员工信息类别不足，请进入“企业管理后台-管理-组织架构”进行添加，完成后重新下载新模板；").append("\n")
                .append("<2>红色字段为必填字段，黑色字段为选填字段；").append("\n")
                .append("<3>员工账号：该字段可初始设定或自动生成，且不可修改；").append("\n")
                .append("<4>部门：上下级部门间用‘-’隔开，且从最上级部门开始，例如“市场部-杭州分部”，多部门用英文的“,”隔开；").append("\n")
                .append("<5>手机号：如果是国内手机号，直接填写手机号即可，如果是国外手机号，需要添加国家码，例如+xx-xxxxxx；").append("\n")
                .append("<6>入职时间：请按2017-04-21这样的格式填写，否则无法正常识别；").append("\n")
                .append("<7>角色：请先到内部通讯录管理-角色先添加好，再到本excel里填入，多角色用英文的“,”隔开；").append("\n");
        noticeRowCell.setCellValue(notice.toString());
        //自动设置行高
        int colLength = noticeRowCell.getStringCellValue().getBytes().length * 5;
        noticeRow.setHeight((short) (colLength));

        //第2行 员工信息：
        Row firstRow = sheet.createRow(1);
        Cell firstRowCell = firstRow.createCell(0);
        firstRowCell.setCellValue("员工信息");
        firstRowCell.setCellStyle(fontCellStyle);
        firstRowCell = firstRow.createCell(12);
        firstRowCell.setCellValue("角色");
        firstRowCell.setCellStyle(fontCellStyle);

        //第3行 表头
        Row headerRow = sheet.createRow(2);
        for (int i = 0; i < EXCEL_IMPORT_HEADER.length; i++) {
            Cell cell = headerRow.createCell(i);
            if(i < 4){
                cell.setCellStyle(fontColorCellStyle);
            }else{
                cell.setCellStyle(fontCellStyle);
            }
            cell.setCellValue(EXCEL_IMPORT_HEADER[i]);
        }

        return sheet;
    }

    public XSSFWorkbook generateLogItemWorkBook(List<EmployeeUploadLogItem> items) throws Exception {
        // 生成模板文件
        XSSFWorkbook wb = new XSSFWorkbook();
        // 设置头信息
        Sheet sheet = wb.createSheet();

        int cellNum = 0;
        for (int i = 0; i < items.size(); i++) {
            cellNum = 0;
            EmployeeUploadLogItem item = items.get(i);
            Row row = sheet.createRow(i);
            row.createCell(cellNum++).setCellValue(item.getUserid());
            row.createCell(cellNum++).setCellValue(item.getName());
            row.createCell(cellNum++).setCellValue(item.getMobile());
            row.createCell(cellNum++).setCellValue(item.getDepartment());
            row.createCell(cellNum++).setCellValue(item.getPosition());
            row.createCell(cellNum++).setCellValue(item.getIdentity());
            row.createCell(cellNum++).setCellValue(item.getGender());
            row.createCell(cellNum++).setCellValue(item.getTelephone());
            row.createCell(cellNum++).setCellValue(item.getEmail());
            row.createCell(cellNum++).setCellValue(item.getOfficeAddress());
            row.createCell(cellNum++).setCellValue(item.getRemark());
            row.createCell(cellNum++).setCellValue(item.getEntryDate());
            row.createCell(cellNum++).setCellValue(item.getRoleName());
        }

        // 自动列宽
        for (int i = 0; i < cellNum; i++) {
            ExcelUtil.autoSizeColumn(sheet, i);
        }
        return wb;

    }

    public XSSFWorkbook generateWorkBook() throws Exception {
        // 生成模板文件
        XSSFWorkbook wb = new XSSFWorkbook();
        // 设置头信息
        Sheet sheet = setSheetCellStyle(wb);

        int cellNum = 0;

        Row row = sheet.createRow(3);
        row.createCell(cellNum++).setCellValue("10011");
        row.createCell(cellNum++).setCellValue("张三（示例）");
        row.createCell(cellNum++).setCellValue("14500000000");
        row.createCell(cellNum++).setCellValue("技术部");
        row.createCell(cellNum++).setCellValue("物业部经理");
        row.createCell(cellNum++).setCellValue("是");
        row.createCell(cellNum++).setCellValue("");
        row.createCell(cellNum++).setCellValue("0755-12345678");
        row.createCell(cellNum++).setCellValue("zhangsan@dingtalkcs.com");
        row.createCell(cellNum++).setCellValue("深圳市南山区金骐智谷大厦1001");
        row.createCell(cellNum++).setCellValue("创始团队成员");
        row.createCell(cellNum++).setCellValue("2015-03-03");
        row.createCell(cellNum++).setCellValue("");

        // 自动列宽
        for (int i = 0; i < cellNum; i++) {
            ExcelUtil.autoSizeColumn(sheet, i);
        }
        return wb;

    }

    public XSSFWorkbook generateWorkBook(List<Employee> list) throws Exception {
        // 生成模板文件
        XSSFWorkbook wb = new XSSFWorkbook();

        // 设置头信息
        Sheet sheet = setSheetCellStyle(wb);

        int cellNum = 0;
        for (int i = 0; i < list.size(); i++) {
            cellNum = 0;
            Employee employee = list.get(i);
            Row row = sheet.createRow(i + 3);
            row.createCell(cellNum++).setCellValue(employee.getUserid());
            row.createCell(cellNum++).setCellValue(employee.getName());
            row.createCell(cellNum++).setCellValue(employee.getMobile());
            row.createCell(cellNum++).setCellValue(String.join(",", employee.getDepartmentName()));
            if(Objects.nonNull(employee.getPositionNos())){
                List<Position> positions = jdbcSession.findArray(Position.class)
                        .in("id", employee.getPositionNos())
                        .exe();
                if(Objects.nonNull(positions)) {
                    List<String> positionNames = positions.stream().map(Position::getName).collect(Collectors.toList());
                    row.createCell(cellNum++).setCellValue(String.join(",", positionNames));
                }
            }else{
                row.createCell(cellNum++).setCellValue("");
            }

            row.createCell(cellNum++).setCellValue(Objects.nonNull(employee.getIdentity()) ? employee.getIdentity().getId().equals("0") ? "否" : "是" : "");
            row.createCell(cellNum++).setCellValue(Objects.nonNull(employee.getGender()) ? employee.getGender().getDesc() : "");
            row.createCell(cellNum++).setCellValue(employee.getTelephone());
            row.createCell(cellNum++).setCellValue(employee.getEmail());
            row.createCell(cellNum++).setCellValue(employee.getOfficeAddress());
            row.createCell(cellNum++).setCellValue(employee.getRemark());
            row.createCell(cellNum++).setCellValue(Objects.nonEmpty(employee.getEntryDate()) ? employee.getEntryDate().substring(0,10) : "");
            row.createCell(cellNum++).setCellValue("");
        }

        // 自动列宽
        for (int i = 0; i < cellNum; i++) {
            ExcelUtil.autoSizeColumn(sheet, i);
        }
        return wb;
    }

    private JSONObject getEmployeeMap(Token token, Employee employee) throws Exception {
        JSONObject result = doveClient.post("/kht-bin/wwout/getEmployeeByKhtId",(http)->{
            JSONObject body = new JSONObject();
            body.put("khtId", employee.getId());
            http.setBody(body.toJSONString());
        });

        if (result.getIntValue("code") == 200) {
            return result.getJSONObject("data");
        }

        return null;
    }

//    @HasPermission("admin:employee:edit")
//    @ReqMapping("/importEmployee")
//    public Object importEmployee(Token token, FileItem item) throws Exception {
//        String fileId =  jsonObject.getString("fileId");
//        String code = jsonObject.getString("code"); //部门code
//        ExclU.
//        byte[] bs = fileUrlConfig.download("/file/download", http->http.addParam("id", fileId));
//        List<String[]> contents = ExcelUtil.readExcel(new ByteArrayInputStream(bs), 6);
//        
//        List<Employee> entitys = new ArrayList<>();
//        for (int i = 0; i < contents.size(); i ++) {
//        	String[] content = contents.get(i);
//        	for (int j = 0; j < content.length - 2; j ++) {
//        		if (Objects.isEmpty(content[j])) {
//        			return Result.error(0, "第" + i + "行：第" + j + "列号不能为空");
//        		}
//        	}
//        	
//        	Employee entity = Pool.newInstance(Employee.class);
//        	entity.setUserid(content[0]);
//        	entity.setName(content[1]);
//        	entity.setMobile(content[2]);
//        	entity.setGender(content[3]);
//	    	entity.setTelephone(content[4]);
//	    	entity.setAddress(content[5]);
//	    	entity.setCompanyNo(companyNo);
//	    	entity.setDepartment(Arrays.asList(code));
//	    	entity.setIs_leader_in_dept(Arrays.asList("0"));
//	    	
//	    	entitys.add(entity);
//        }
//
//        JSONResult rs = check(entitys);
//        if (!rs.isOk()){
//        	return rs;
//        }
//
//        List<String> errors = new ArrayList<>();
//        employeeService.saveEmployees(companyNo, entitys, errors);
//
//        if (Objects.nonEmpty(errors)) {
//            return Result.error(0, String.join(",", errors));
//        }
//        
//        return Result.success();
//    }

}
